<template>
  <div v-if="isLoggedIn" style="height: 100vh;">
    <el-container style="height: 100%;">
      <el-aside width="200px" style="background-color: #545c64;">
        <el-menu :default-active="$route.path" class="el-menu-vertical" background-color="#545c64" text-color="#fff"
          active-text-color="#ffd04b" router>
          <template v-for="route in menuRoutes" :key="route.path">
            <el-menu-item :index="route.path" v-if="!route.children">
              <el-icon>
                <component :is="route.meta.menu.icon" />
              </el-icon>
              <span>{{ route.meta.menu.title }}</span>
            </el-menu-item>
            <el-submenu v-else :index="route.path">
              <template #title>
                <el-icon>
                  <component :is="route.meta.menu.icon" />
                </el-icon>
                <span>{{ route.meta.menu.title }}</span>
              </template>
              <el-menu-item v-for="child in route.children" :key="child.path" :index="child.path">
                {{ child.meta.menu.title }}
              </el-menu-item>
            </el-submenu>
          </template>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="border-bottom: 1px solid #eee;">
          <div class="header-content">
            <span style="font-size: 18px; font-weight: bold;">智能档案管理系统</span>
            <!-- 未登录时显示登录按钮，已登录时显示用户信息 -->
            <div class="auth-area">
              <el-button v-if="!isLoggedIn" type="primary" @click="goToLogin">
                登录
              </el-button>
              <div class="user-info" v-else>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    <span style="margin-left: 8px;">{{ userName }}</span>
                    <el-icon><arrow-down /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <!-- <el-dropdown-item @click="handleProfile">个人中心</el-dropdown-item> -->
                      <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </el-header>

        <el-main>
          <router-view v-slot="{ Component }">
            <keep-alive :include="cachedViews">
              <component :is="Component" :key="$route.fullPath" />
            </keep-alive>
          </router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
  <div v-else style="height: 100vh;">
    <router-view v-slot="{ Component }">
      <component :is="Component" :key="$route.fullPath" />
    </router-view>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from './stores/user.js'
import { useAppStore } from './stores/app.js'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

const menuRoutes = computed(() => {
  return router.options.routes.filter(route =>
    route.meta?.menu?.show && route.path !== '/login'
  )
})

// 计算属性：判断是否登录
const isLoggedIn = computed(() => !!userStore.token)

// 计算属性：获取用户名（从 userInfo 解析）
const userName = computed(() => {
  return userStore.userInfo?.realName || null
})

const cachedViews = computed(() => appStore.cachedViews)

// 监听路由变化以缓存页面
watch(
  () => router.currentRoute.value,
  (to) => {
    if (to.meta?.keepAlive && !appStore.cachedViews.includes(to.name)) {
      appStore.addCachedView(to.name)
    }
  },
  { immediate: true }
)

function handleLogout() {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout()
    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {
    // 用户取消
  })
}

function goToLogin() {
  router.push('/login')
}
</script>

<style scoped>
.el-menu-vertical {
  border-right: none;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  width: 100%;
}

.el-menu-vertical {
  height: 100%;
  border: none;
}

.auth-area {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
}
</style>